package cn.itcast.wanxinp2p.account.service.impl;


import cn.itcast.wanxinp2p.account.entity.pojo.Account;
import cn.itcast.wanxinp2p.account.mapper.AccountMapper;
import cn.itcast.wanxinp2p.account.model.account.AccountDTO;
import cn.itcast.wanxinp2p.account.model.account.AccountLoginDTO;
import cn.itcast.wanxinp2p.account.model.account.AccountRegisterDTO;
import cn.itcast.wanxinp2p.account.service.AccountService;


import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.domain.StatusCode;
import cn.itcast.wanxinp2p.common.exception.AccountErrorCode;
import cn.itcast.wanxinp2p.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/3/30  15:43
 */
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private AccountMapper accountMapper;
    @Value("${sms.enable}")
    private boolean smsEnable;

    @Override
    public RestResponse getSMSCode(String mobile) {
        //TODO
        // 发起远程请求调用 短信微服务 发送短信   RestTemplate
        // http://localhost:56085/sailing/generate?effectiveTime=300&name=sms
        // {"mobile":"13566668888"}
        /*返回数据：直接将短信服务的结果返回即可
            {
                "code": 0,
                "msg": "",
                "result": {
                    "key": "sms:70ba933b095b4b5c90ee314045fd9003",
                    "content": null
                }
            }
         */

        String url = "http://localhost:56085/sailing/generate?effectiveTime=300&name=sms";
        Map<String, String> params = new HashMap<>();
        params.put("mobile", mobile);
        RestResponse result = restTemplate.postForObject(url, params, RestResponse.class);

/*        JSONObject jsonObject = JSON.parseObject(result);
        Object result1 = jsonObject.get("result");*/

        return result;

    }

    @Override
    public Integer checkMobile(String mobile, String key, String code) {
          /* 1、远程调用 短信微服务 校验验证码是否正确
              Post请求：
              http://localhost:56085/sailing/verify?name=sms&verificationKey=sms:70ba933b095b4b5c90ee314045fd9003&verificationCode=707339
              根据结果判断验证码校验是否成功，如果失败，则抛出 AccountErrorCode.E_140152 异常

            2、如果验证码正确，还需要根据手机号 去 account 表中查询手机号是否存在
            	如果存在返回 1，否则返回 0
        */
        //String url = "http://localhost:56085/sailing/verify?name=sms&verificationKey=sms:70ba933b095b4b5c90ee314045fd9003&verificationCode=707339";
        String url = "http://localhost:56085/sailing/verify?name=sms&verificationKey=" + key + "&verificationCode=" + code;
        restTemplate.postForObject(url, null, RestResponse.class);
        List<Account> list = accountMapper.findByPhone(mobile);
        return list.size() > 0 ? 1 : 0;
       /* 返回结果：
        {
            "code": 0,
            "msg": "",
            "result": 1(成功) / 0(失败)
        }
        */
    }

    /**
     * 账户注册
     *
     * @param registerDTO 注册信息
     * @return
     */
    @Override
    public AccountDTO register(AccountRegisterDTO registerDTO) {
        //TODO
        List<Account> byPhone = accountMapper.findByPhone(registerDTO.getMobile());
        if (byPhone.size() != 0) {
            throw new BusinessException(AccountErrorCode.E_140141);
        }
        Account account = new Account();
        BeanUtils.copyProperties(registerDTO, account);
        account.setStatus(StatusCode.STATUS_OUT.getCode());
        account.setDomain("b");
        accountMapper.insertAccount(account);

        //设置状态
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setUsername(registerDTO.getUsername());
        accountDTO.setMobile(registerDTO.getMobile());
        accountDTO.setStatus(1);
        accountDTO.setDomain("a");
        return accountDTO;
    }

    @Override
    public AccountDTO login(AccountLoginDTO accountLoginDTO) {
        //1、查询用户，注意此处需要根据前端传递的 AccountLoginDTO的domain做判断：
        String domain = accountLoginDTO.getDomain();
        //  如果值是 c 表示是c端用户，需要根据手机号查询
        //  否则是b端用户，需要根据用户名查询
        List<Account> byPhone = null;
        if (domain.equalsIgnoreCase("c")) {
            byPhone = accountMapper.findByPhone(accountLoginDTO.getMobile());
        }
        if (domain.equalsIgnoreCase("a")) {
            byPhone = accountMapper.findByUser(accountLoginDTO.getUsername());
        }
        //2、判断用户是否存在，如果不存在，直接抛出 AccountErrorCode.E_130104 异常
        if (byPhone.size() == 0) {
            throw new BusinessException(AccountErrorCode.E_130104);
        }
        AccountDTO accountDTO = new AccountDTO();
        BeanUtils.copyProperties(accountLoginDTO, accountDTO);
        accountDTO.setStatus(StatusCode.STATUS_IN.getCode());
        //3、如果 smsEnable=true ，说明是短信验证码登录，不做密码校验。直接返回
        if (smsEnable = true) {
            return accountDTO;
        }
        //4、验证密码，如果密码错误则抛出 AccountErrorCode.E_130105 异常
        for (Account account : byPhone) {
            if (!accountLoginDTO.getPassword().equals(account.getPassword())) {
                throw new BusinessException(AccountErrorCode.E_130105);
            }
        }
        return accountDTO;
    }
}